<template>
  <div class="table-container">
    <!-- 表格 -->
    <el-table :data="tableData" class="custom-table">
      <el-table-column
        prop="productName"
        label="产品名称"
        width="120"
        align="center"
      />
      <el-table-column
        prop="pictureNumber"
        label="图号"
        width="120"
        align="center"
      />
      <el-table-column
        prop="material"
        label="材质"
        width="120"
        align="center"
      />
      <el-table-column
        prop="packageNumber"
        label="件数(pcs)"
        width="120"
        align="center"
      />
      <el-table-column
        prop="unitWeight"
        label="预计单重(kg/件)"
        width="100"
        align="center"
      />
      <el-table-column
        prop="unitPrice"
        label="单价(USD/pc)"
        width="100"
        align="center"
      />
      <el-table-column
        prop="productCategory"
        label="产品分类"
        align="center"
        width="180px"
      />
    </el-table>

    <!-- 自定义缩略图上传 -->
    <div class="upload-container">
      <span>参数图片：</span>
      <el-upload
        class="upload-list"
        :action="host + '/upload'"
        list-type="picture-card"
        :auto-upload="true"
        multiple
        :file-list="fileList"
        :on-remove="handleRemove"
        :on-preview="handlePictureCardPreview"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
      >
        <template v-if="fileList.length < maxUploadCount">
          <el-icon><Plus /></el-icon>
        </template>
      </el-upload>
    </div>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>

    <!-- 发送请求按钮 -->
    <el-col :span="8" class="button-group">
      <el-button color="#2F4050" @click="handleSave">保存</el-button>
      <el-button type="primary" @click="handleBack">返回</el-button>
    </el-col>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, type UploadFile } from "element-plus";
import { useRouter } from "vue-router";
import { saveProductParamePicture } from "@/api/supplier/supplier";
import host from "@/utils/env.js";

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const tableData = ref<any[]>([]); // 存储表格数据
const fileList = ref<UploadFile[]>([]); // 存储上传的图片列表
const maxUploadCount = ref(5); // 最多可上传的图片数量
const router = useRouter();

onMounted(() => {
  const storedData = localStorage.getItem("rowData");
  if (storedData) {
    try {
      // console.log("从 localStorage 获取的数据：", storedData);
      const parsedData = JSON.parse(storedData);

      if (typeof parsedData === "object" && !Array.isArray(parsedData)) {
        tableData.value = [parsedData];
      } else if (Array.isArray(parsedData)) {
        tableData.value = parsedData;
      } else {
        console.error("存储的数据格式不正确", parsedData);
      }

      // **回显已有的图片**
      let paramePicture = parsedData.paramePicture;

      // **如果是字符串，转换为数组**
      if (typeof paramePicture === "string") {
        paramePicture = paramePicture
          .split(/[,;\s]+/)
          .map(url => url.trim())
          .filter(url => url);
      }

      if (Array.isArray(paramePicture)) {
        fileList.value = paramePicture.map(url => ({
          name: url.split("/").pop() || "图片",
          url: url.startsWith("http") ? url : host + url, // 确保完整 URL
          status: "success" // 确保符合 UploadFile 类型
        })) as UploadFile[];
      }

      console.log("回显图片 fileList:", fileList.value);
    } catch (e) {
      console.error("解析存储的数据时发生错误", e);
    }
    localStorage.removeItem("rowData");
  } else {
    console.log("没有找到存储的 rowData 数据");
  }
});

// **移除图片**
const handleRemove = (file: UploadFile) => {
  fileList.value = fileList.value.filter(f => f !== file);
  console.log("移除图片:", file);
};

// **预览图片**
const handlePictureCardPreview = (file: UploadFile) => {
  if (file.url) {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true;
  } else {
    console.error("文件没有 URL:", file);
  }
};

// **上传成功**
const handleUploadSuccess = (response: any, file: UploadFile) => {
  console.log("上传成功响应:", response);

  if (response?.data) {
    file.url = host + response.data; // 拼接完整 URL
    ElMessage.success(`上传成功: ${file.name}`);

    // **确保 fileList 里正确存储了文件**
    fileList.value.push({ ...file, url: file.url });

    console.log("更新后的 fileList:", fileList.value);
  } else {
    ElMessage.warning(`上传成功，但未返回 URL: ${file.name}`);
    console.warn("上传成功但未返回 URL:", response);
  }
};

// **上传失败**
const handleUploadError = (err: any, file: UploadFile) => {
  console.error("上传失败:", err, file);
  ElMessage.error(
    `上传失败: ${file.name}，错误信息: ${err.message || JSON.stringify(err)}`
  );
};

// **保存到数据库**
const handleSave = async () => {
  if (!tableData.value.length) {
    console.error("无表格数据，无法保存");
    return;
  }

  const id = tableData.value[0].id;
  if (!id) {
    console.error("未找到 ID，无法保存");
    return;
  }

  // **检查 fileList 是否正确存储了文件**
  console.log("当前 fileList:", fileList.value);

  const paramePicture = fileList.value.map(file => file.url).filter(url => url);

  console.log("要保存的图片路径>>>", paramePicture);

  if (!paramePicture.length) {
    console.error("未找到有效的图片路径，无法保存");
    return;
  }

  const requestData = { id, paramePicture };

  try {
    const response = await saveProductParamePicture(requestData);
    console.log("保存成功:", response);
    ElMessage.success("图片保存成功");
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("图片保存失败");
  }
};
// **返回按钮操作**
const handleBack = async () => {
  router.push({ name: "parameterSupport" });
};
</script>

<style scoped>
.table-container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  gap: 20px;
}

.custom-table {
  width: auto;
  max-width: 950px;
}

.upload-container {
  width: 100%;
  display: flex;
  justify-content: flex-start;
}

.upload-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  width: 100%;
  max-width: 600px;
}

.upload-list >>> .el-upload {
  width: 120px !important;
  height: 120px !important;
}

/* 按钮组样式  */
.button-group .el-button {
  margin-right: 10px;
}

.button-group .el-button:last-child {
  margin-right: 0; /* 确保最后一个按钮没有额外间距 */
}
</style>
